package com.wonders.demo.util;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class SignUtils {

	private static final String ALGORITHM = "RSA";

	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private static final String DEFAULT_CHARSET = "UTF-8";


	/**
	 * 签名
	 * @param content
	 * @param privateKey
	 * @return
	 */
	public static String sign(String content, String privateKey) {
		try {
			PrivateKey priKey =getPrivateKey(privateKey);

			java.security.Signature signature = java.security.Signature
					.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 验签
	 * @param content
	 * @param sign
	 * @param publicKey
	 * @return
	 */
	public static boolean verify(String content, String sign, String publicKey){
		try {

			PublicKey pubKey = getPublicKey(publicKey);

			java.security.Signature signature = java.security.Signature
					.getInstance(SIGN_ALGORITHMS);
			signature.initVerify(pubKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));
			return signature.verify(Base64.decode(sign));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static PublicKey getPublicKey(String publicKey){
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decode(publicKey));
        KeyFactory keyFactory = null;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pk = keyFactory.generatePublic(keySpec);
            return pk;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static PrivateKey getPrivateKey(String privateKey){
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = null;
        try {
            keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            return priKey;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	public static String encrypt(String text,String publicKey){
        //RSA加密
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
			byte[] bytes = text.getBytes();
			int inputLen = bytes.length;
			int offLen = 0;//偏移量
			int i = 0;
			ByteArrayOutputStream bops = new ByteArrayOutputStream();
			while(inputLen - offLen > 0){
				byte [] cache;
				if(inputLen - offLen > 117){
					cache = cipher.doFinal(bytes, offLen,117);
				}else{
					cache = cipher.doFinal(bytes, offLen,inputLen - offLen);
				}
				bops.write(cache);
				i++;
				offLen = 117 * i;
			}
			bops.close();
			byte[] encryptedData = bops.toByteArray();
			String encodeToString = Base64.encode(encryptedData);
			return encodeToString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	public static String decrypt(String text,String privateKey){
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));
			byte[] bytes = Base64.decode(text);
			int inputLen = bytes.length;
			int offLen = 0;
			int i = 0;
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			while(inputLen - offLen > 0){
				byte[] cache;
				if(inputLen - offLen > 128){
					cache = cipher.doFinal(bytes,offLen,128);
				}else{
					cache = cipher.doFinal(bytes,offLen,inputLen - offLen);
				}
				byteArrayOutputStream.write(cache);
				i++;
				offLen = 128 * i;

			}
			byteArrayOutputStream.close();
			byte[] byteArray = byteArrayOutputStream.toByteArray();
			return new String(byteArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

	public static void main(String[] args) {
		String aPublicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTnC2pT2b2uKOcfs9SCRgBZMCg\n" +
				"cVCqAZSHkBAJcwqjQleugAEbfOr9XIxPIAXORCagqulKiR3bVMt2Hl+0IdUoBpVs\n" +
				"xAqyWEu2py8c5+47fRQU4+OjUNKr/rtWFZsZPNVjS0RPlOH5Of4T/MUnARn1aceJ\n" +
				"VPMyM3Fv1fcVALXd7wIDAQAB";
		String aPrivateKey="MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBANOcLalPZva4o5x+\n" +
				"z1IJGAFkwKBxUKoBlIeQEAlzCqNCV66AARt86v1cjE8gBc5EJqCq6UqJHdtUy3Ye\n" +
				"X7Qh1SgGlWzECrJYS7anLxzn7jt9FBTj46NQ0qv+u1YVmxk81WNLRE+U4fk5/hP8\n" +
				"xScBGfVpx4lU8zIzcW/V9xUAtd3vAgMBAAECgYEAsV/aTm9GKUy/p/ALrAH/Yzum\n" +
				"01XofXhxneg96Q3LPunfQV/+jaH5/4HSAokfFLS/hDF+94FTy4OaQFpZck5hsnGr\n" +
				"YVBRDEtKqT3rBkLfKYS6LnrK/IxjlUt4mXneYf9Rf8QiXXvJNr1WQQ/SX1gnUf/P\n" +
				"gafKkkUnDzS1Sb0A9CECQQD9Su8hQSpt5qds4aBUHyqNOLFaDFF1ZUEIW9u51kh4\n" +
				"mUC3QbMhnPULq9+Jq9w3Cj6+RoXWViA8AkbSsvONDEL3AkEA1d8w8NViKrppfe3q\n" +
				"atSN0eAD75MK4HgU6aa6ICgwW09BVjdWdE0HgXZwtG/Cnhz5wIOgNX60Vhp3FvxM\n" +
				"FziGyQJBALssHYt4aU8vS/eEv4KKSVp0U3JUefmDakwv/S3VsFYWAaGqFiI3p0kJ\n" +
				"qDVG34N4uabH3Gzn1ggiMo3OmXVYYz8CQQCpM+fbUWZV2Z8mMvkXxcvhtDJI8vNS\n" +
				"/Y3GANMWJ9WCF+TgGe27G0oJ4bNu/VBimRf6d+hjCjgQOuXm+HoWkPEJAkEAvdAV\n" +
				"d/SqeLUQtT1YzqH1tGcazxSxVVb51zz1HWdzqS9U83NjGkI3NgFyfJ+qfunHLAmg\n" +
				"9HxkntdwymEcxyNbnw==";
		String bPublicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxGvOgmfgFCYyF8aiN/jbR9V5Y\n" +
				"KbRYj+/k3kfk/ajxGDshSFuG9i2/5hsoG3uHS3DRdJYF8i9BMA+cZJerd1d2z1hF\n" +
				"tB5LOVCgUFUg0FREgktTR9Z8Hk5VM2QWhm8nvl6gRYIpixkaK98HtqTPgw3UqeLh\n" +
				"s65OqMIMX6HYyj4GzQIDAQAB";
		String bPrivateKey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALEa86CZ+AUJjIXx\n" +
				"qI3+NtH1XlgptFiP7+TeR+T9qPEYOyFIW4b2Lb/mGygbe4dLcNF0lgXyL0EwD5xk\n" +
				"l6t3V3bPWEW0Hks5UKBQVSDQVESCS1NH1nweTlUzZBaGbye+XqBFgimLGRor3we2\n" +
				"pM+DDdSp4uGzrk6owgxfodjKPgbNAgMBAAECgYAcL4viXV6pfpGMp58JqhGTbJdt\n" +
				"NIXtKkslg3KxsOT4KcEPVPKsEfXJ+pcL1QPdzlXQH9vYami22S1C2IeC1GVo0SeA\n" +
				"6cv6LD05W8UTrcV9brTUJgANKGu/DSbTUQYl+jf2ouF2k4V9a6uHiLdVL1SW0EBY\n" +
				"m5gwvt9+7iHHzW54yQJBAOeJ79xe7EgJ5uDAf6lihyVEqt2Nc83CgzkTrlZNnNnJ\n" +
				"/gt4SoIqvb8Mx0dCBb7jSBTaCKkDgr8W6tfwXy5xvF8CQQDD0NZTh0/RVYKUML8f\n" +
				"8egQ7m+ZQjrQ19K9vbeRop9apDkbKLZp+o+lTLMZ8xBKh1+L+UP1lpzPZlykfbyV\n" +
				"5oxTAkArCAPAHRQkv1JdaulO/bTIRF7NFkDzeLcSoInCGGKSR2wjjZOrZW4mV6Wh\n" +
				"pK+UroDy/yKk5rYh9Yxn3ZCS/ShZAkEAt28eJ9ddJTuWfF4B3NoPTDUgpBBP6q4T\n" +
				"RB3CJhKSdyXaPR/xaewHvpDQQqHZBAg2sHhMenah5QP+CzWigUYc8wJAAmgbYOHg\n" +
				"E8zJgVyjQlXIN3+Tb11Cdenbv70pLEBUg57X8YGfiztPcLZ3viFK44By/iGhZkRm\n" +
				"zcyR2I8IEyGmyg==";

		String a="client_id=036QNArdFU&code=smy:54547917-acb9-4137-a81d-efe96bf38926&timestamp=1552021859385&token=1b38a286-7efa-4efa-8e1e-bf92d8a5340b";
		String b="client_id=036QNArdFU&code=37yQLZ&redirect_uri=http://wonders.liuzhou.gov.cn/budongchan&timestamp=1552021859385";
		//		String sign=sign(a,aPrivateKey);
//		System.out.println(sign);
		String sign=sign(a,bPrivateKey);
		System.out.println("验签："+verify(a,sign,bPublicKey));
		String rsign="c5sM4l8WiJDPA/oi4MUdA8mISwEVKrXJRXtdKiWISj0IuFHD9Tq8CmQXmNO2hxu0fTjLfIs6IG6PX7H91TOECv7hNRbHCuCN0WZO70KE3dGvnO5M31AFTFUgD8TXFppzlgvo8IhuvO2/DB1J9MVr5cOOvnFYy0ZGN9YkVWJXgrs=";
		System.out.println("加签："+sign);
		System.out.println("加签："+rsign);
		System.out.println("----------");
		System.out.println(sign(b,bPrivateKey));
		System.out.println(verify(a,"RSwo8/ozrTbpIhD88MTiyWi7FREpOYAnv00usuUtfKJOw+QbFsiq1KA7yw+aTiDDZE2ZR2oLOIw2cECKicE8F9wIyOcbeH4PBXwOgDNnMIpp72EI/JP4QxiNYNWOvgO+xPVpZ4yRElKSlmOL/nDVzS5vuzt4NUCqR9kAyMto+NY=","MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxGvOgmfgFCYyF8aiN/jbR9V5YKbRYj+/k3kfk/ajxGDshSFuG9i2/5hsoG3uHS3DRdJYF8i9BMA+cZJerd1d2z1hFtB5LOVCgUFUg0FREgktTR9Z8Hk5VM2QWhm8nvl6gRYIpixkaK98HtqTPgw3UqeLhs65OqMIMX6HYyj4GzQIDAQAB"));

		System.out.println(aPrivateKey);
		System.out.println(bPublicKey);

		String c="assssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
				"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
				"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
				"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

		System.out.println(c);

		System.out.println(decrypt(encrypt(c,aPublicKey),aPrivateKey));

		System.out.println(verify("baHjVYh1OxHXj4L/AjTnSf9vnpPcIefxA0Pbsz05AnC5E4oiThocYKs5Bx8QqCtLHxMfzQ3Oiegp1J9UY6/i8iBv1n2+5jUxUg1oclOUizZzL2pUKCghsaM4jUY0OKhO7wrWXgiFY8The619BPLjh3KJs8dBxaujEd7hgvPC9YI=","wDDu1+Bl8nciFX2pu5Xr8sLpDOQPIFGtUHBiWn30+FjgzgMRGRZebtf11PCnWyzvJA6kFDtBboIbaKUmi1keomAHo7e37QTjzZWxOB5fmwZ/Uaa8hcI/jjlnD5jyfH/9Vr5Y4QTlkaQ/0Aa7ytH4YkVhGnV7I3IflVEZ6twkIRo=",aPublicKey));
		System.out.println(decrypt("GZscWL4GFfSYYmyohU4Hrm8DfHnoGGWIdyqyutiH+1KsydK5Q5echr2+j8PRp7SveCpi8Cq/hBYBVhQLXkRMi3cd1iB8ZNYr2fTQpfjL8CPg5FZjj4wu252hYM5Ewt56yhoozHU6ePbwt132JWhWByWiGqfCsSUsW0sG3uFSBwk=",bPrivateKey));
	}



}
